package com.chushouya.order.service.common.impl;

import com.chushouya.common.shunfeng.ShunfengExpressUtil;
import com.chushouya.common.shunfeng.dto.ContactInfo;
import com.chushouya.common.shunfeng.dto.SfCreateOrderDTO;
import com.chushouya.common.shunfeng.dto.ShunfengResponse;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.constants.LogisticsTypeEnum;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderLogisticsEntity;
import com.chushouya.order.dao.repository.OrderAddressRepository;
import com.chushouya.order.dao.repository.OrderLogisticsRepository;
import com.chushouya.order.dto.admin.orderlogistics.OrderLogisticsQuery;
import com.chushouya.order.service.common.OrderExpressService;
import com.general.framework.core.exception.Ex;
import com.chushouya.order.service.common.OrderLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;


@Service
@Slf4j
public class OrderExpressServiceImpl implements OrderExpressService {



    @Resource
    private ShunfengExpressUtil shunfengExpressUtil;


    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Resource
    private OrderLogisticsRepository orderLogisticsRepository;

    @Resource
    private OrderLogService orderLogService;


    /**
     * 获取用户地址信息
     * @return
     */
    private OrderAddressEntity getUserAddress(Long orderId) {
        OrderAddressEntity orderAddressEntity = orderAddressRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderAddressEntity)) {
            throw Ex.business("订单地址信息不存在");
        }
        return orderAddressEntity;
    }

    /**
     * 获取用户寄件信息
     * @param orderId
     * @return
     */
    private OrderLogisticsEntity getOrderLogistics(Long orderId) {
        OrderLogisticsQuery query = new OrderLogisticsQuery();
        query.setOrderId(orderId);
        query.setType(LogisticsTypeEnum.USER_SEND.value());
        OrderLogisticsEntity orderLogisticsEntity = orderLogisticsRepository.selectOne(query);
        if (Objects.isNull(orderLogisticsEntity)) {
            throw Ex.business("订单快递信息不存在");
        }
        return orderLogisticsEntity;
    }


    @Override
    public SfCreateOrderDTO reserve(OrderEntity orderEntity) {
        SfCreateOrderDTO sfCreateOrderDTO = null;
        final Long orderId = orderEntity.getOrderId();
        final OrderAddressEntity userAddress = this.getUserAddress(orderId);
        ContactInfo senderInfo = new ContactInfo();
        senderInfo.setContact(userAddress.getUserName());
        senderInfo.setMobile(userAddress.getUserPhone());
        senderInfo.setProvince(userAddress.getProvince());
        senderInfo.setCity(userAddress.getCity());
        senderInfo.setCounty(userAddress.getDistrict());
        senderInfo.setAddress(userAddress.getAddress());
        String cargoName = orderEntity.getProductName();
        Date appointmentTime = orderEntity.getAppointStartTime();
        try {
            sfCreateOrderDTO = shunfengExpressUtil.createExpressOrder(senderInfo, cargoName, appointmentTime);
        } catch (Exception e) {
            log.error("预约快递失败：{}", e.getMessage());
            throw Ex.business("预约快递失败 {}", e.getMessage());
        }

        return sfCreateOrderDTO;
    }

    @Override
    public SfCreateOrderDTO reserveReturn(OrderEntity orderEntity) {
        SfCreateOrderDTO sfCreateOrderDTO = null;
        final Long orderId = orderEntity.getOrderId();
        final OrderAddressEntity userAddress = this.getUserAddress(orderId);
        ContactInfo senderInfo = new ContactInfo();
        senderInfo.setContact(userAddress.getUserName());
        senderInfo.setMobile(userAddress.getUserPhone());
        senderInfo.setProvince(userAddress.getProvince());
        senderInfo.setCity(userAddress.getCity());
        senderInfo.setCounty(userAddress.getDistrict());
        senderInfo.setAddress(userAddress.getAddress());
        String cargoName = orderEntity.getProductName();
        Date appointmentTime = orderEntity.getAppointStartTime();
        try {
            sfCreateOrderDTO = shunfengExpressUtil.createReturnExpressOrder(senderInfo, cargoName, appointmentTime);
        } catch (Exception e) {
            log.error("预约退货快递失败：{}", e.getMessage());
            throw Ex.business("预约退货快递失败 {}", e.getMessage());
        }

        return sfCreateOrderDTO;
    }

    @Override
    public boolean cancelExpress(Long orderId) {
        log.info("开始取消快递订单，顺丰订单号: {}", orderId);
        
        if (Objects.isNull(orderId) ) {
            log.error("取消快递失败：订单号为空");
            throw Ex.business("顺丰订单号不能为空");
        }
        OrderLogisticsEntity logistics = getOrderLogistics(orderId);
        final String sfOrderId = logistics.getOrderCode();
        try {
            ShunfengResponse response = shunfengExpressUtil.cancelExpressOrder(sfOrderId);

            if (response.isSuccess()) {
                log.info("取消快递订单成功，顺丰订单号: {}", sfOrderId);
                orderLogService.addOrderActionLog(
                        orderId,
                        OrderActionEnum.FOLLOW_ORDER.value(),
                        Strings.format("取消顺丰快递订单成功")
                );
                return true;
            } else {
                log.error("取消快递订单失败，顺丰订单号: {}, 错误信息: {}", 
                        sfOrderId, response.getApiErrorMsg());
                orderLogService.addOrderActionLog(
                        orderId,
                        OrderActionEnum.FOLLOW_ORDER.value(),
                        Strings.format("取消顺丰快递 {}",response.getApiErrorMsg())
                );
                throw Ex.business("取消快递失败: {}", response.getApiErrorMsg());
            }
            
        } catch (Exception e) {
            log.error("取消快递订单异常，顺丰订单号: {}, 异常信息: {}", sfOrderId, e.getMessage(), e);
            throw Ex.business("取消快递异常: {}", e.getMessage());
        }
    }


}
